<?php
namespace Api\Controller;
use Think\Controller;
class CreditController extends CommonController {
    //积分商城首页
    public function index(){


    }

    //积分签到页面
    public function sign_index()
    {
        $arr = [];
        //查出系统设置。连续签到奖励，总签到奖励
        $info = M('credit_sign_set')->where(['wid'=>session('wid')])->find();
        $info['sign_con_credit'] = explode(',',$info['sign_con_credit']);
        $info['sign_con_day'] = explode(',',$info['sign_con_day']);

        //查询连续签到领取记录
        $log = M('credit_log')->where(['openid'=>I('openid')])->select();

        if(is_array($info['sign_con_day']) && !empty($info['sign_con_day']))
        {
            if(!$log){
                //没有领取连续签到
                foreach($info['sign_con_day'] as $k=>$v){
                    $arr[$k] = ['sign_con_day'=>$v,'sign_con_credit'=>$info['sign_con_credit'][$k],'gift'=>'no'];
                }
            }else{
                 //领取过连续签到
                foreach($info['sign_con_day'] as $k=>$v){
                    $arr[$k] = ['sign_con_day'=>$v,'sign_con_credit'=>$info['sign_con_credit'][$k],'gift'=>getVal($log,'orderid',$v)?"ok":'no'];
                }
            }

        }
        $info['arr'] = $arr;
        //查出签到的内容
        $sign = M('credit_sign')->where(['openid'=>I('openid')])->select();
        foreach($sign as $k=>$v){
            $sign[$k]['year'] = date('Y',strtotime($v['time']));
            $sign[$k]['month'] =date('m',strtotime($v['time']));
            $sign[$k]['day'] = date('d',strtotime($v['time']));
        }
        $info['sign'] = $sign;
        //查出最后一条签到信息
        $info['new'] = M('credit_sign')->where(['openid'=>I('openid')])->order('time desc')->find();

        //
        $info['member'] = getMember(session('wid'),I('openid'));
        $this->ajaxReturn($info);
    }


    //签到操作
    public function sign()
    {
        $openid = I('openid');
        //先查询有没有签到过
        $map['openid'] =$openid;
        $map['wid'] = session('wid');

        //最后一次签到
        $sign = M('credit_sign')->where($map)->order('time desc')->find();
        //查出签到设置
        $set = M('credit_sign_set')->where(['wid'=>session('wid')])->find();
        $msg = '签到成功';
        //首次签到
        if(!$sign){
            $data['credit'] = $set['first'];
            $data['num'] = 1; //连续签到数
            $data['maxnum'] = 1;//最大连续签到数
            $msg = '首次签到，奖励'.$set['first'].'分';
        }else{
            $data['credit'] = $set['normal'];
            //判断是否连续签到
            $cha = (strtotime(date('Y-m-d'))- strtotime($sign['time']))/(60*60*24) ;
            if($cha == 1){
                //连续签到
                $data['num'] = $sign['num'] +1;
                $data['maxnum'] = $data['num']>$sign['maxnum']?$data['num']:$sign['maxnum'];

            }
            elseif($cha > 1){
                //非连续签到
                $data['num'] = 1;
                $data['maxnum'] = $sign['maxnum'];
            }else{
                //已经签到了
                $this->ajaxReturn(['code'=>200,'msg'=>'今天已签到']);
            }


        }
        $data['openid'] = $openid;
        $data['wid'] =session('wid');
        $data['time'] = date('Y-m-d');
        $re = M('credit_sign')->add($data);
        //M('member')->where(['openid'=>I('openid')])->setInc(['credit'=>$data['credit']]);
        //积分产生
        addCredit($openid, $data['credit'], $re, session('wid'), 7);

        if($re){
            $this->ajaxReturn(['code'=>0,'msg'=>$msg]);
        }else{
            $this->ajaxReturn(['code'=>200,'msg'=>'网络繁忙，请稍后再试！']);
        }
    }
    /*
 * 获取页面数据
 *
 * */
    public function getInfo () {
        $list = [];
        //轮播信息
        $flash = M('credit_flash')->where(['wid' => session('wid')])->order('order_num desc')->select();
        $list['flash'] = $flash;
        //分类
        $cate = M('credit_type')->where(['wid' => session('wid')])->order('sort desc')->select();
        $list['cate'] = $cate;
        //精品专区
        $jing = M('credit_goods')->where(['wid' => session('wid')])->order('order_num desc')->limit('0, 4')->select();
        $list['jing'] = $jing;

        $list['member'] = getMember(session('wid'),I('openid'));
        $this->ajaxReturn($list);
    }

    /*
     * 商品详情
     *
     * */
    public function getGoodsItem () {
        $id = $_GET['id'];
        $info = M('credit_goods')->where(['id' => $id])->find();
        //参与记录
        $sql = "SELECT
                    o.*,m.headimgurl,m.nickname
                FROM
                    tp_credit_order o
                LEFT JOIN tp_member m on m.openid =o.openid
                WHERE
                    (pay_money > 0 AND is_pay = 1)
                OR (pay_money = 0)
                ORDER BY o.time desc";
        $list = M()->query($sql);
        $info['record'] = $list;
        $info['record_count'] = count($list);

        $this->ajaxReturn($info);
    }
    //连续签到领取积分
    public function sign_gift()
    {
        $data['openid'] = I('openid');
        $data['credit'] = I('credit');
        $data['orderid'] = I('day');//通过day查对应的积分
        $data['type'] = 8;  //0店铺入驻 1同城卡 2信息发布 3店铺升级 4商品核销 5送礼物 6餐饮  7签到 8连续签到积分
        $data['wid'] = session('wid');
        $data['time'] = date("Y-m-d H:i:s");
        $re = M('credit_log')->add($data);

        //member表加积分
        $me = M('member')->where(['openid'=>I('openid')])->setInc(['credit'=>I('credit')]);
        if($re){
            $this->ajaxReturn(['code'=>0,'msg'=>"成功领取".$data['credit']."积分"]);
        }else{
            $this->ajaxReturn(['code'=>200,'msg'=>'网络繁忙，请稍后再试！']);
        }
    }

    //签到列表
    public function sign_list()
    {
        //连续签到
        $arr['list1'] = M('credit_sign')
                        ->alias('s')
                        ->join('tp_member m on m.openid = s.openid')
                        ->where(['s.wid'=>session('wid')])
                        ->order('maxnum desc')
                        ->group('s.openid')
                        ->select();
        $arr['list2'] = M('credit_sign')
            ->field("m.*,count(*) as c")
            ->alias('s')
            ->join('tp_member m on m.openid = s.openid')
            ->where(['s.wid'=>session('wid')])
            ->order('c desc')
            ->select();
        $this->ajaxReturn($arr);
    }

    public function getCateGoods () {
        //每页几条
        $num = 6;
        //页码
        $page = $_GET['page'];
        $start = $page * $num;
        $type_id = $_GET['id'];
        $catename = M('credit_type')->where(['id' => $type_id])->find();
        $where['wid'] = session('wid');
        if ($type_id) {
            $where['type_id'] = $type_id;
        }
        $jing = M('credit_goods')->where($where)->order('order_num desc')->limit("$start, $num")->select();
        $list['type_name'] = $catename;
        $list['goods'] = $jing;

        $this->ajaxReturn($list);
    }

    /*
     * 积分兑换
     * 
     * */
    public function exchange () {
        $openid = $_POST['openid'];
        $goods_id = $_POST['goods_id'];
        $name = $_POST['username'];
        $tel = $_POST['tel'];
        if (!$name) {
            $this->ajaxReturn(['error' => 1, 'msg' => '姓名不能为空!']);
        }
        if (!$tel) {
            $this->ajaxReturn(['error' => 1, 'msg' => '电话不能为空!']);
        }
        //商品信息
        $good = M('credit_goods')->where(['id' => $goods_id])->find();
        if($good['stock' == 0]){
            $this->ajaxReturn(['error' => 1, 'msg' => '商品库存不足!']);
        }
        //兑换人信息
        $user = M('member')->where(['wid' => session('wid'), 'openid' => $openid])->find();
        if ($good['rate1'] > $user['credit']) {
            $this->ajaxReturn(['error' => 1, 'msg' => '积分余额不足!']);
        }
        //兑换
        $needInt = $good['rate1'];
        $userInt = $user['credit'];
        $afterInt = $user['credit'] - $good['rate1'];

        //add order
        $order_data = [
            'wid' => session('wid'),
            'openid' => $openid,
            'out_trade_no' => $this->build_order_no(),
            'credit' => $good['rate1'],
            'pay_money' =>$good['rate2'],
            'goodsid' => $goods_id,
            'time' => date('Y-m-d H:i:s', time()),
            'status' => 1,
            'name' => $name,
            'tel' => $tel
        ];
        $c_order = M('credit_order')->add($order_data);
        //积分变动
        addCredit($openid,-$good['rate1'],$c_order,session('wid'),9);

       //是否需要支付
        if($good['rate2']>0){
            $map['wid'] = session('wid');
            $wechat = M("Wechat")->where($map)->find();
            $appid = $wechat['appid'];
            $mch_id = $wechat['mch_id'];
            $key = $wechat['partner_key'];

            $url = "https://".$_SERVER['HTTP_HOST'].U("Notify/creditShop");

            vendor('Weixinpay.WxPayJsApiPay');
            $tools = new \JsApiPay();
            $input = new \WxPayUnifiedOrder();

            $remark = "智联同城";

            $input->SetBody($remark);
            $input->SetAttach('积分兑换');
            $input->SetOut_trade_no($order_data['out_trade_no']);
            $input->SetTotal_fee(($good['rate2']*100));
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));

            $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openid);
            $input->SetAppid($appid);
            $input->SetMch_id($mch_id);

            try{
                $wxorder = \WxPayApi::unifiedOrder($input, $key);
            }catch(Exception $e){
                $arr = array("err_code"=>400,"err_msg"=>$e->getMessage().$good['rate2']);
                $this->ajaxReturn($arr);
            }
            if($wxorder['return_code'] == "FAIL"){
                $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg'].$good['rate2']);
                $this->ajaxReturn($arr);
            }
            try{
                $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
            }catch(Exception $e){
                $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
                $this->ajaxReturn($arr);
            }
           // $jsApiParameters['info'] = 101;
            echo $jsApiParameters;
            exit;
        }

        if ( $c_order ) {
            M('credit_goods')->where(['id'=>$good['id']])->setDec('stock');
            $this->ajaxReturn(['error' => 0, 'msg' => '兑换成功']);
        } else {
            $this->ajaxReturn(['error' => 1, 'msg' => '网络忙']);
        }
    }
    //店铺积分商城兑换
    public function exchangeShop () {
        $openid = $_POST['openid'];
        $goods_id = $_POST['goods_id'];
        $name = $_POST['username'];
        $tel = $_POST['tel'];
        if (!$name) {
            $this->ajaxReturn(['error' => 1, 'msg' => '姓名不能为空!']);
        }
        if (!$tel) {
            $this->ajaxReturn(['error' => 1, 'msg' => '电话不能为空!']);
        }
        //商品信息
        $good = M('credit_goods')->where(['id' => $goods_id])->find();
        if($good['stock' == 0]){
            $this->ajaxReturn(['error' => 1, 'msg' => '商品库存不足!']);
        }
        //会员卡
        $card2 = M('shop_mycard')->where(['shop_id'=>$good['shop_id'],'openid'=>$_POST['openid']])->find();
        if ($good['rate1'] > $card2['integral']) {
            $this->ajaxReturn(['error' => 1, 'msg' => '会员卡积分不足!']);
        }

        //add order
        $data['wid'] = session('wid');
        $data['rechargelog_id'] = 0;
        $data['mycard_id'] = $card2['id'];
        $data['shop_id'] = $good['shop_id'];
        $data['openid'] = $_POST['openid'];
        $data['integral'] = $good['rate1'];
        $data['remark'] = '兑换商品花费';
        $data['create_time'] = date("Y-m-d H:i:s");

        //添加积分记录
        M('shop_integral_log')->add($data);
        $re = M('shop_mycard')->where(['id'=>$card2['id']])->setDec('integral',$good['rate1']);

        if ( $re ) {
            M('credit_goods')->where(['id'=>$good['id']])->setDec('stock');
            $this->ajaxReturn(['error' => 0, 'msg' => '兑换成功']);
        } else {
            $this->ajaxReturn(['error' => 1, 'msg' => '网络忙']);
        }
    }



    //积分兑换记录
    public function getRecord()
    {
        $map = "(pay_money > 0 AND is_pay = 1) OR (pay_money = 0) and openid ='".I('openid')."'";
        $list['record'] = M('credit_order')
                ->alias('o')
                ->field('o.*,g.name,g.img,g.id as goodsid')
                ->join('tp_credit_goods g on g.id = o.goodsid','LEFT')
                ->where($map)
                ->order('o.time desc')
                ->select();
        $list['member'] = getMember(session('wid'),I('openid'));
        $this->ajaxReturn($list);
    }

    //积分明细
    public function credit_detail()
    {
        $member  = getMember(session('wid'),I('openid'));
        $list = M('credit_log')->alias('c')->field('c.*,m.headimgurl,m.nickname')
            ->join('tp_member m on m.openid =c.openid',"left")->where(['c.openid'=>$member['openid']])->order('c.time desc')->select();
        $this->ajaxReturn($list);
    }


    //店铺积分商城商品列表
    public function getshopGoods () {
        //每页几条
        $num = 6;
        //页码
        $page = $_GET['page'];
        $start = $page * $num;
        $shop_id = $_GET['shop_id'];

        $where['wid'] = session('wid');
        $where['shop_id'] = $shop_id;

        $jing = M('credit_goods')->where($where)->order('order_num desc')->limit("$start, $num")->select();

        $list['goods'] = $jing;

        $this->ajaxReturn($list);
    }

}